//
//  RHMultipeImagePickView.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/10.
//

#import "RHMultipeImagePickView.h"
#import "RHAddImageCell.h"
#import "RHAddImageModel.h"
@interface RHMultipeImagePickView()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic ,strong) UICollectionView *collectionView;

@property (nonatomic ,strong) NSMutableArray *imageItemtArray;//图片视图

@property (nonatomic ,weak) UIViewController *controller;
@end

@implementation RHMultipeImagePickView

-(instancetype)initWithController:(UIViewController*)controller;
{
    if (self = [super init]) {
        self.controller = controller;
        [self setupUI];
    }
    return  self;
}


-(void)setImageUrls:(NSArray *)imageUrls
{
    _imageUrls = imageUrls;
    kWeakSelf;
    [self.imageItemtArray removeAllObjects];
    [imageUrls enumerateObjectsUsingBlock:^(NSString*  _Nonnull url, NSUInteger idx, BOOL * _Nonnull stop) {
        RHAddImageModel *model = [[RHAddImageModel alloc]init];
        model.imageUrl = url;
        model.isEditing = weakSelf.isEditing;
        [weakSelf.imageItemtArray addObject:model];
    }];
    
    [self.collectionView reloadData];

}


-(void)setIsEditing:(BOOL)isEditing
{
    _isEditing = isEditing;
    [self.imageItemtArray enumerateObjectsUsingBlock:^(RHAddImageModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        model.isEditing = self.isEditing;
    }];
    [self.collectionView reloadData];
}

-(NSArray*)needUploadImageUrls
{
    NSMutableArray *mtbArr = [NSMutableArray array];
    [self.imageItemtArray enumerateObjectsUsingBlock:^(RHAddImageModel*  _Nonnull imageModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if(imageModel.imageUrl){
            [mtbArr addObject:imageModel.imageUrl];
        }
    }];
    return mtbArr.copy;
}
-(NSArray*)needUploadImageArr
{
    NSMutableArray *mtbArr = [NSMutableArray array];
    [self.imageItemtArray enumerateObjectsUsingBlock:^(RHAddImageModel*  _Nonnull imageModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if(imageModel.image){
            [mtbArr addObject:imageModel.image];
        }
    }];
    return mtbArr.copy;
}


-(void)setupUI
{
    self.backgroundColor = UIColor.grayColor;
    kWeakSelf;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    CGFloat itemWidth = (kUI_WINDOW_W - 30 - (10 * 2))/3;
    layout.itemSize = CGSizeMake(itemWidth, itemWidth);
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 10, 10);
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_collectionView registerClass:[RHAddImageCell class] forCellWithReuseIdentifier:@"addImageCell"];
    [self addSubview:_collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.height.offset(itemWidth);
    }];
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if(self.isEditing){
        return self.imageItemtArray.count>0?self.imageItemtArray.count+1:1;
    }
    return self.imageItemtArray.count;
}

-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    kWeakSelf;
    RHAddImageCell *itemCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"addImageCell" forIndexPath:indexPath];
    itemCell.imgModel = [self.imageItemtArray safeObjectAtIndex:indexPath.item];
    itemCell.addPictureBlcok = ^(RHAddImageModel *imageModel){
        [weakSelf addPicAction:imageModel];
    };
    itemCell.deletePictureBlcok = ^(RHAddImageModel *imageModel){
        [weakSelf.imageItemtArray removeObject:imageModel];
        [weakSelf.collectionView reloadData];
    };
    return itemCell;
}


#pragma mark - Action
- (void)addPicAction:(RHAddImageModel*)imageModel{
    
    [self norSheetViewWithTitle:@""
                        mess:@""
                            theme:UIColor.blackColor
                            oneTitle:@"拍照".rh_localized
                               twoTitle:@"相册".rh_localized
                                       oneHandler:^{
        [self addPhotoFromCamera:(RHAddImageModel*)imageModel];
    }
                                       twoHandler:^{
        [self addPhotoFromAlbum:NO imageModel:imageModel];
        
   }];
}


//从相机拍照
- (void)addPhotoFromCamera:(RHAddImageModel*)imageModel{
    if (![ZLPhotoManager haveCameraAuthority]) {
        NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoCameraAuthorityText), kAPPName];
        [SVProgressHUD showInfoWithStatus:message];
        return;
    }
    
    ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
    camera.allowTakePhoto = YES;
    camera.allowRecordVideo = NO;
    
    kWeakSelf;
    camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
        
        RHAddImageModel *model = [[RHAddImageModel alloc]init];
        model.image = image;
        model.isEditing = weakSelf.isEditing;
        [weakSelf.imageItemtArray addObject:model];
        [weakSelf.collectionView reloadData];
       
    };
    [self.controller showDetailViewController:camera sender:nil];
}

//从相册选择图片
//hasCamera -- 是否附带拍照
- (void)addPhotoFromAlbum:(BOOL)hasCamera imageModel:(RHAddImageModel*)imageModel{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置语言
    actionSheet.configuration.languageType = (ZLLanguageType)[[kUserDefaults objectForKey:@"ZLLanguage"]integerValue];
    //是否升序排列，预览界面不受该参数影响
    actionSheet.configuration.sortAscending = NO;
    //设置相册内部显示拍照按钮
    actionSheet.configuration.allowTakePhotoInLibrary = hasCamera?YES:NO;
    //设置在内部拍照按钮上实时显示相机俘获画面
    actionSheet.configuration.showCaptureImageOnTakePhotoBtn = hasCamera?YES:NO;
    //设置是否允许选择原图
    actionSheet.configuration.allowSelectOriginal = YES;
    //设置是否允许选择视频
    actionSheet.configuration.allowSelectVideo = NO;
    //设置是否允许选择gif
    actionSheet.configuration.allowSelectGif = NO;
    //是否显示选中图片的index 默认YES
    actionSheet.configuration.showSelectedIndex = NO;
    //是否允许编辑
    actionSheet.configuration.allowEditImage = NO;
    
    
    //预览选择模式下 拍照/相册/取消 的字体颜色 默认 blackColor
    actionSheet.configuration.previewTextColor = kCOLOR_HEX(@"#666666");
    //遮罩层颜色， 默认 blackColor alpha 0.2
    actionSheet.configuration.selectedMaskColor = [[UIColor blackColor] colorWithAlphaComponent: 0.7f];
    // 导航条颜色，默认 rgb(44, 45, 46)
    actionSheet.configuration.navBarColor = kCOLOR_HEX(@"#FFFFFF");;
    // 导航标题颜色，默认 white
    actionSheet.configuration.navTitleColor = kCOLOR_HEX(@"#222222");
    // 底部工具栏按钮 可交互 状态标题颜色，默认 white
    actionSheet.configuration.bottomBtnsNormalTitleColor = kCOLOR_HEX(@"#222222");
    //底部工具栏按钮 可交互 状态背景颜色，默认rgb(80, 169, 56)
    actionSheet.configuration.bottomBtnsNormalBgColor = kCOLOR_HEX(@"#e9e9e9");
    //底部工具栏按钮 不可交互 状态背景颜色，默认rgb(39, 80, 32)
    //actionSheet.configuration.bottomBtnsDisableBgColor = CDisBtnColor;
    // 底部工具条底色，默认 rgb(44, 45, 46)
    actionSheet.configuration.bottomViewBgColor = kCOLOR_HEX(@"#ffffff");
    //设置照片 cell的圆角弧度
    actionSheet.configuration.cellCornerRadio = 5.0;
    //状态栏样式 默认 UIStatusBarStyleLightContent
    actionSheet.configuration.statusBarStyle = UIStatusBarStyleDefault;
    //设置照片最大预览数
    //actionSheet.configuration.maxPreviewCount = 2;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 3 - self.imageItemtArray.count;
    
    actionSheet.sender = self.controller;

    [actionSheet showPhotoLibrary];
    
    kWeakSelf;
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        
        
//        UIImage *image = images[0];
//        NSData *imageData = UIImageJPEGRepresentation(image, 1.0f);
//        NSLog(@"--->图片大小: %ld k", (long)(imageData.length / 1024));
//        [weakSelf.pictureView setPictureImageArray:images];
        
        [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            RHAddImageModel *model = [[RHAddImageModel alloc]init];
            model.image = obj;
            model.isEditing = weakSelf.isEditing;
            [weakSelf.imageItemtArray addObject:model];
        }];
        [weakSelf.collectionView reloadData];
    
    }];

    actionSheet.selectImageRequestErrorBlock = ^(NSArray<PHAsset *> * _Nonnull errorAssets, NSArray<NSNumber *> * _Nonnull errorIndex) {
    };
    
    actionSheet.cancleBlock = ^{
        
       
    };
}

//MARK: NOTE == 普通Sheet弹窗，按钮1和按钮2  主题色
- (void)norSheetViewWithTitle:(NSString *)title
                         mess:(NSString *)mess
                        theme:(UIColor *)themeColor
                     oneTitle:(NSString *)oneTitle
                     twoTitle:(NSString *)twoTitle
                   oneHandler:(dispatch_block_t)oneHandler
                   twoHandler:(dispatch_block_t)twoHandler{
    // 底部按钮
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle: @"取消".rh_localized style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
    }];
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle: oneTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (oneHandler) {
            oneHandler();
        }
    }];

    QMUIAlertAction *action3 = [QMUIAlertAction actionWithTitle: twoTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (twoHandler) {
            twoHandler();
        }
    }];
    
    QMUIAlertController *alertController = [[QMUIAlertController alloc] initWithTitle: title message: mess preferredStyle:QMUIAlertControllerStyleActionSheet];
    /// sheet内容的圆角，默认值是 13，以保持与系统默认样式一致
    alertController.sheetContentCornerRadius = 6;
    /// sheet按钮高度，默认值是 57，以保持与系统默认样式一致
    alertController.sheetButtonHeight = 58;
    alertController.sheetContentMargin = UIEdgeInsetsMake(10, 12, 10, 12);
    /// sheet的最大宽度，默认值是5.5英寸的屏幕的宽度减去水平的 sheetContentMargin
    //alertController.sheetContentMaximumWidth = 320;
    
    NSMutableDictionary *titleAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetTitleAttributes];
    titleAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#222222");
    titleAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    titleAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail textAlignment: NSTextAlignmentCenter];
    
    /// sheet标题样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontBoldMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetTitleAttributes = titleAttributs;
    
    NSMutableDictionary *messageAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetMessageAttributes];
     messageAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#444444");
       messageAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:14];
       messageAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail];
    /// sheet信息样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetMessageAttributes = messageAttributs;
    
    //alert头部（非按钮部分）背景色
    alertController.alertHeaderBackgroundColor = UIColorWhite;
    //alert按钮背景色
    alertController.alertButtonBackgroundColor = UIColorWhite;
    //alert上分隔线颜色
    alertController.alertSeparatorColor = kCOLOR_HEX(@"#f5f5f5");
    /// alert头部title和message之间的间距
    alertController.alertTitleMessageSpacing = 5;
    
    NSMutableDictionary *buttonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetButtonAttributes];
    buttonAttributes[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#666666");
    buttonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];

    alertController.sheetButtonAttributes = buttonAttributes;
    
    NSMutableDictionary *cancelButtonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetCancelButtonAttributes];
    cancelButtonAttributes[NSForegroundColorAttributeName] = themeColor;
    cancelButtonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    alertController.sheetCancelButtonAttributes = cancelButtonAttributes;
    
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    [alertController showWithAnimated:YES];
}
-(NSMutableArray *)imageItemtArray
{
    if(!_imageItemtArray){
        _imageItemtArray = [NSMutableArray array];
    }
    return _imageItemtArray;
}

@end
